<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true">
        <el-form-item label="目录名字" prop="catalogName">
          <el-input
            placeholder="请输入目录名字"
            v-model="catalogSearchParams.catalogName"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleTreeList"
          ></el-input>
        </el-form-item>
        <el-form-item label="目录类型" prop="catalogType">
          <el-select
            placeholder="请选择目录类型"
            v-model="catalogSearchParams.catalogType"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleTreeList"
          >
            <el-option
              v-for="koi in koiDicts.blog_catalog_type"
              :key="koi.dictValue"
              :label="koi.dictLabel"
              :value="koi.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目录状态" prop="catalogStatus">
          <el-select
            placeholder="请选择目录状态"
            v-model="catalogSearchParams.catalogStatus"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleTreeList"
          >
            <el-option
              v-for="koi in koiDicts.sys_switch_status"
              :key="koi.dictValue"
              :label="koi.dictLabel"
              :value="koi.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain @click="handleCatalogSearch" v-auth="['blog:catalog:search']">{{
            $t("button.search")
          }}</el-button>
          <el-button type="danger" icon="refresh" plain @click="resetCatalogSearch">{{ $t("button.reset") }}</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['blog:catalog:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">{{ $t("button.add") }}</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['blog:catalog:update']">
          <el-button type="success" icon="edit" plain @click="handleUpdate()" :disabled="single">{{
            $t("button.update")
          }}</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['blog:catalog:delete']">
          <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">{{
            $t("button.delete")
          }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" icon="close" plain @click="handleBack()">{{ $t("button.close") }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" icon="Sort" plain @click="toggleExpandAll()">{{ $t("button.expand") }}</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleTreeList"></KoiToolbar>
      </el-row>

      <div class="h-20px"></div>
      <!-- 数据表格 -->
      <el-table
        v-if="refreshTreeTable"
        v-loading="catalogLoading"
        border
        :data="catalogTableList"
        @selection-change="handleSelectionChange"
        :default-expand-all="isExpandAll"
        :expand-row-keys="expandKey"
        row-key="catalogId"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :empty-text="$t('msg.null')"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column :label="$t('table.number')" prop="catalogId" width="80px" align="center" type="index"></el-table-column>
        <el-table-column
          label="目录名字"
          prop="catalogName"
          width="260px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="展开/折叠" prop="isSpread" width="100px" align="center">
          <template #default="scope">
            <el-switch
              v-if="scope.row.catalogType === '1'"
              v-model="scope.row.isSpread"
              active-text="展开"
              inactive-text="折叠"
              active-value="0"
              inactive-value="1"
              :inline-prompt="true"
              @click="handleSpread(scope.row)"
            >
            </el-switch>
            <template v-else></template>
          </template>
        </el-table-column>
        <el-table-column label="目录类型" prop="catalogType" width="100px" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="koiDicts.blog_catalog_type" :value="scope.row.catalogType"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="目录状态" prop="catalogStatus" width="100px" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.catalogStatus"
              :active-text="$t('dict.sys_switch_status.open')"
              :inactive-text="$t('dict.sys_switch_status.stop')"
              active-value="0"
              inactive-value="1"
              :inline-prompt="true"
              @change="handleSwitch(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="文章ID"
          prop="articleId"
          width="200px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="是否选择" prop="articleId" width="120px" align="center">
          <template #default="scope">
            <div v-if="scope.row.catalogType === '2'">
              <el-tag :type="scope.row.articleId ? 'primary' : 'danger'">{{ scope.row.articleId ? "已选择" : "未选择" }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sorted" width="100px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180px" align="center"></el-table-column>
        <el-table-column
          :label="$t('table.operate')"
          align="center"
          width="190"
          fixed="right"
          v-auth="['blog:catalog:update', 'blog:catalog:delete']"
        >
          <template #default="{ row }">
            <el-tooltip :content="$t('button.add')" placement="top" v-if="row.catalogType === '1'">
              <el-button
                type="primary"
                icon="CirclePlus"
                circle
                plain
                @click="handleAdd(row)"
                v-auth="['blog:catalog:add']"
              ></el-button>
            </el-tooltip>
            <el-tooltip :content="$t('button.update')" placement="top">
              <el-button
                type="success"
                icon="Edit"
                circle
                plain
                @click="handleUpdate(row)"
                v-auth="['blog:catalog:update']"
              ></el-button>
            </el-tooltip>
            <el-tooltip :content="$t('button.delete')" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
                v-auth="['blog:catalog:delete']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="添加文章" placement="top" v-if="row.catalogType === '1'">
              <el-button
                type="info"
                icon="Files"
                circle
                plain
                @click="handleChooseMultipleArticle(row)"
                v-auth="['blog:catalog:choose']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="选择文章" placement="top" v-if="row.catalogType === '2'">
              <el-button
                type="warning"
                icon="Tickets"
                circle
                plain
                @click="handleChooseSingleArticle(row)"
                v-auth="['blog:catalog:choose']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加 OR 修改 -->
      <KoiDrawer
        ref="koiDrawerRef"
        :title="title"
        @koiConfirm="handleDrawerConfirm"
        @koiCancel="handleDrawerCancel"
        :loading="confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="auto" status-icon>
            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="目录名字" prop="catalogName">
                  <el-input type="textarea" v-model="form.catalogName" :rows="3" placeholder="请输入目录名字" maxlength="256" show-word-limit clearable />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="目录类型" prop="catalogType">
                  <el-select placeholder="请选择目录类型" v-model="form.catalogType" clearable @change="handleSorted">
                    <el-option
                      v-for="koi in koiDicts.blog_catalog_type"
                      :key="koi.dictValue"
                      :label="koi.dictLabel"
                      :value="koi.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="目录状态" prop="catalogStatus">
                  <el-select placeholder="请选择目录状态" v-model="form.catalogStatus" clearable>
                    <el-option
                      v-for="koi in koiDicts.sys_switch_status"
                      :key="koi.dictValue"
                      :label="koi.dictLabel"
                      :value="koi.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="是否展开" prop="isSpread">
                  <el-select placeholder="请选择是否展开" v-model="form.isSpread" clearable>
                    <el-option
                      v-for="koi in koiDicts.sys_switch_status"
                      :key="koi.dictValue"
                      :label="koi.dictLabel"
                      :value="koi.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="父级目录" prop="parentId">
                  <!-- 级联选择框 -->
                  <el-cascader
                    placeholder="请选择上级数据"
                    v-model="form.parentId"
                    :options="cascaderOptions"
                    :props="{
                      expandTrigger: 'hover',
                      emitPath: false,
                      checkStrictly: true
                    }"
                    :show-all-levels="false"
                    filterable
                    clearable
                    class="w-260px"
                  >
                    <template #default="{ node, data }">
                      <span>{{ data.label }}</span>
                      <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                    </template>
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="排序" prop="sorted">
                  <el-input-number v-model="form.sorted" placeholder="请输入数字" :min="1" clearable />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </KoiDrawer>
      <!-- 选择文章 -->
      <KoiDialog
        ref="koiDialogRef"
        :title="title"
        @koiConfirm="handleDialogConfirm"
        @koiCancel="handleDialogCancel"
        :loading="confirmLoading"
        :width="1000"
        :height="530"
        top="6vh"
      >
        <template #content>
          <div class="p-6px">
            <!-- 搜索条件 -->
            <el-form v-show="showSearch" :inline="true">
              <el-form-item label="文章标题" prop="articleTitle">
                <el-input
                  placeholder="请输入文章标题"
                  v-model="articleSearchParams.articleTitle"
                  clearable
                  style="width: 220px"
                  @keyup.enter.native="handleListPage"
                ></el-input>
              </el-form-item>
              <el-form-item label="文章类别" prop="categoryId">
                <el-select
                  placeholder="请选择文章类别"
                  v-model="articleSearchParams.categoryId"
                  clearable
                  filterable
                  style="width: 220px"
                  @keyup.enter.native="handleListPage"
                >
                  <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="search" plain @click="handleArticleSearch" v-auth="['blog:article:search']">{{
                  $t("button.search")
                }}</el-button>
                <el-button type="danger" icon="refresh" plain @click="resetArticleSearch">{{ $t("button.reset") }}</el-button>
              </el-form-item>
            </el-form>
            <div class="h-20px"></div>
            <!-- 数据表格 -->
            <el-table
              ref="articleTableRef"
              v-loading="articleLoading"
              border
              :height="390"
              :data="tableList"
              :empty-text="$t('msg.null')"
              @selection-change="handleArticleSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column
                :label="$t('table.number')"
                prop="articleId"
                width="80px"
                align="center"
                type="index"
              ></el-table-column>
              <el-table-column
                label="文章标题"
                prop="articleTitle"
                width="200px"
                align="center"
                :show-overflow-tooltip="true"
              ></el-table-column>
              <el-table-column label="图片" prop="picture" width="120px" align="center" :show-overflow-tooltip="true">
                <template #default="scope">
                  <div class="flex flex-justify-center">
                    <el-image
                      class="max-w-100% h-52px rounded-8px"
                      :src="scope.row.picture"
                      fit="contain"
                      :preview-teleported="true"
                      :preview-src-list="[scope.row.picture]"
                    >
                      <!-- 这个地方若加载不出来，暂时用一个默认图片代替 -->
                      <!-- https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png -->
                      <template #error>
                        <el-image
                          src="https://i.postimg.cc/zBRKsrdv/carousel66.jpg"
                          fit="cover"
                          :preview-teleported="true"
                          :preview-src-list="['https://i.postimg.cc/zBRKsrdv/carousel66.jpg']"
                          class="max-w-100% h-52px rounded-8px"
                        ></el-image>
                      </template>
                    </el-image>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="文章类型" prop="articleType" width="120px" align="center">
                <template #default="scope">
                  <KoiTag :tagOptions="koiDicts.blog_article_type" :value="scope.row.articleType"></KoiTag>
                </template>
              </el-table-column>
              <el-table-column
                label="文章类别"
                prop="categoryName"
                width="150px"
                align="center"
                :show-overflow-tooltip="true"
              ></el-table-column>
              <el-table-column label="文章标签" prop="tagList" width="450px" align="center" :show-overflow-tooltip="true">
                <template #default="scope">
                  <div class="flex flex-justify-center gap-3px">
                    <el-tag v-for="item in scope.row.tagList" :key="item.tagId" :type="getRandomTagColor()">{{
                      item.tagName
                    }}</el-tag>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <div class="h-20px"></div>
            <!-- 分页 -->
            <el-pagination
              background
              v-model:current-page="articleSearchParams.pageNo"
              v-model:page-size="articleSearchParams.pageSize"
              v-show="total > 0"
              :page-sizes="[10, 20, 50, 100, 200]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleListPage"
              @current-change="handleListPage"
            />
          </div>
        </template>
      </KoiDialog>
    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="catalogPage">
import { nextTick, ref, reactive, onMounted } from "vue";
import { koiMsgSuccess, koiMsgError, koiMsgWarning } from "@/utils/koi.ts";
import { ElMessageBox } from "element-plus";
import { handleTree } from "@/utils/index.ts";
import {
  list,
  cascaderList,
  getById,
  add,
  update,
  deleteById,
  batchDelete,
  updateStatus,
  updateSpread,
  updateArticleId,
  batchAdd,
  getSorted
} from "@/api/blog/catalog/index.ts";
import { listLibraryChooseArticlePage } from "@/api/blog/article/index.ts";
import { listCategoryElSelect } from "@/api/blog/category/index.ts";
import { useI18n } from "vue-i18n";
import { useKoiDict } from "@/hooks/dicts/index.ts";
import { useRoute, useRouter } from "vue-router";
import useTabsStore from "@/stores/modules/tabs.ts";

const tabsStore = useTabsStore();
const route = useRoute();
const router = useRouter();
const { koiDicts } = useKoiDict(["blog_catalog_type", "sys_switch_status", "blog_article_type"]);
const { t } = useI18n();
// 表格加载动画Loading
const catalogLoading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 表格数据
const catalogTableList = ref<any>([]);
// 传递参数
const routeParam = ref();

// 查询参数
const catalogSearchParams = ref<any>({
  catalogName: undefined,
  catalogType: undefined,
  catalogStatus: undefined,
  libraryId: routeParam.value
});

/** 重置搜索参数 */
const catalogResetSearchParams = () => {
  catalogSearchParams.value = {
    catalogName: undefined,
    catalogType: undefined,
    catalogStatus: undefined,
    libraryId: routeParam.value
  };
};

/** 搜索 */
const handleCatalogSearch = () => {
  handleTreeList();
};

/** 重置 */
const resetCatalogSearch = () => {
  catalogResetSearchParams();
  handleTreeList();
};

/** 树形表格查询 */
const handleTreeList = async () => {
  try {
    catalogTableList.value = []; // 重置表格数据
    catalogLoading.value = true;
    const res: any = await list(catalogSearchParams.value);
    catalogTableList.value = handleTree(res.data, "catalogId", "parentId");
    handleExpandKey(res.data);
    catalogLoading.value = false;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 数据表格 */
const handleTreeData = async () => {
  try {
    const res: any = await list(catalogSearchParams.value);
    catalogTableList.value = handleTree(res.data, "catalogId", "parentId");
    handleExpandKey(res.data);
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

const colors = ["primary", "success", "info", "warning", "danger"];
/* 获取随机标签颜色 */
const getRandomTagColor = () => {
  const randomIndex = Math.floor(Math.random() * colors.length);
  return colors[randomIndex];
};

onMounted(() => {
  routeParam.value = route.params.libraryId || ""; // 有值
  catalogSearchParams.value.libraryId = routeParam.value;
  // 获取表格数据
  handleTreeList();
});

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用
/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.catalogId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

// 级联下拉框
let cascaderOptions = ref<any>([]);
/** 级联下拉框 */
const handleCascader = async () => {
  try {
    cascaderOptions.value = [];
    const res: any = await cascaderList(routeParam.value);
    cascaderOptions.value = handleTree(res.data, "value");
    cascaderOptions.value.unshift({
      label: "最顶级数据",
      value: "0",
      parentId: "-1"
    });
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

// 重新渲染表格状态
const refreshTreeTable = ref(true);
// 是否展开，默认展开
const isExpandAll = ref(false);
/** 展开/折叠 */
const toggleExpandAll = () => {
  refreshTreeTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTreeTable.value = true;
  });
};

/** 获取最新排序数字 */
const handleSorted = async () => {
  try {
    const res: any = await getSorted(form.value.catalogType, routeParam.value);
    form.value.sorted = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 添加 */
const handleAdd = (row?: any) => {
  // 打开抽屉
  koiDrawerRef.value.koiOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = t("button.add");
  handleCascader();
  form.value.parentId = "0";
  form.value.isSpread = "1";
  // 目录
  form.value.catalogType = "1";
  if (row) {
    nextTick(() => {
      form.value.parentId = row?.catalogId + "";
      // 文章
      form.value.catalogType = "2";
      form.value.isSpread = "1";
      handleSorted();
    });
  } else {
    handleSorted();
  }
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  try {
    const res: any = await getById(id);
    form.value = res.data;
    form.value.parentId = res.data.parentId + "";
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 打开抽屉
  koiDrawerRef.value.koiOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = t("button.update");
  const id = row ? row.catalogId : ids.value[0];
  handleCascader();
  // 回显数据
  handleEcho(id);
};

// 添加 OR 修改对话框Ref
const koiDrawerRef = ref();
// 标题
const title = ref();
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  catalogName: undefined,
  catalogType: undefined,
  catalogStatus: "0",
  parentId: undefined,
  libraryId: routeParam.value,
  catalogId: undefined,
  isSpread: "1",
  sorted: 1
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });
  form.value = {
    catalogName: undefined,
    catalogType: undefined,
    catalogStatus: "0",
    parentId: undefined,
    libraryId: routeParam.value,
    catalogId: undefined,
    isSpread: "1",
    sorted: 1
  };
};

/** 表单规则 */
const rules = reactive({
  catalogName: [{ required: true, message: "请输入目录名字", trigger: "blur" }],
  catalogType: [{ required: true, message: "请选择目录类型", trigger: "blur" }],
  catalogStatus: [{ required: true, message: "请选择目录状态", trigger: "blur" }],
  parentId: [{ required: true, message: "请输入父级目录", trigger: "blur" }],
  libraryId: [{ required: true, message: "请输入知识库ID", trigger: "blur" }],
  isSpread: [{ required: true, message: "请选择是否展开", trigger: "blur" }],
  sorted: [{ required: true, message: "请输入排序", trigger: "blur" }]
});

// 确定按钮是否显示Loading
const confirmLoading = ref(false);

/** 确定  */
const handleDrawerConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      if (form.value.catalogId != null && form.value.catalogId != "") {
        try {
          await update(form.value);
          koiMsgSuccess(t("msg.success"));
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleTreeList();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      } else {
        try {
          await add(form.value);
          koiMsgSuccess(t("msg.success"));
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleTreeList();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      }
    } else {
      koiMsgError(t("msg.validFail"));
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleDrawerCancel = () => {
  koiDrawerRef.value.koiClose();
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.catalogId;
  if (id == null || id == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmDelete"), t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteById(id);
        handleTableData();
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmDelete"), t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await batchDelete(ids.value);
        handleTableData();
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 状态开关 */
const handleSwitch = (row: any) => {
  let text = row.catalogStatus === "0" ? t("dict.sys_switch_status.open") : t("dict.sys_switch_status.stop");
  if (!row.catalogId || !row.catalogStatus) {
    row.catalogStatus = row.catalogStatus == "0" ? "1" : "0";
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmWant") + "[" + text + "]-[" + row.catalogTitle + "]?", t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await updateStatus(row.catalogId, row.catalogStatus);
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        row.catalogStatus = row.catalogStatus == "0" ? "1" : "0";
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      row.catalogStatus = row.catalogStatus == "0" ? "1" : "0";
      koiMsgWarning(t("msg.cancelled"));
    });
};

// 展开数据
const expandKey = ref();

/** 展开节点 */
const handleExpandKey = (data: any) => {
  if (data != null && data.length != 0) {
    expandKey.value = [];
    const resultList: string[] = [];
    data.forEach((obj: any) => {
      if (obj.parentId == "0" && obj.isSpread == "0") {
        resultList.push(obj.catalogId);
      }
      if (obj.parentId != "0" && obj.isSpread == "0") {
        resultList.push(obj.catalogId);
        resultList.push(obj.parentId);
      }
    });
    // 过滤数据
    const uniqueArray = [...new Set(resultList)];
    console.log("展开节点", uniqueArray);
    // 数组必须转为String类型才生效
    expandKey.value = uniqueArray.map(String);
  } else {
    expandKey.value = [];
  }
};

/** 是否展开 */
const handleSpread = async (row: any) => {
  if (!row.catalogId || !row.isSpread) {
    koiMsgWarning("请选择需要展开的数据");
    return;
  }
  try {
    await updateSpread(row.catalogId, row.isSpread);
    handleTreeData();
    koiMsgSuccess(t("msg.success"));
  } catch (error) {
    handleTreeData();
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 选择文章对话框 */
const koiDialogRef = ref();
const articleTableRef = ref();
const catalogId = ref();
// 切换单选确认，还是多选确认
const switchStatus = ref(0);

/** 选择文章 */
const handleChooseSingleArticle = async (row: any) => {
  switchStatus.value = 1;
  catalogId.value = row?.catalogId ? row?.catalogId : "";
  articleSearchParams.value.articleId = row?.articleId ? row?.articleId : "";
  // 打开对话框
  koiDialogRef.value.koiOpen();
  // 等待 handleListPage 完成
  const success = await handleListPage();
  handleListCategoryElSelect();
  // 标题
  title.value = "选择文章";
  if (success) {
    // 反选表格数据[测试]
    // articleTableRef.value!.toggleRowSelection(tableList.value[0]);
    // 反选表格数据
    nextTick(() => {
      const invertSelection = tableList.value.find((item: any) => {
        return item?.articleId === row?.articleId;
      });
      if (invertSelection) {
        articleTableRef.value!.toggleRowSelection(invertSelection);
      }
    });
  }
};

/** 取消 */
const handleDialogCancel = () => {
  koiDialogRef.value.koiClose();
};

// 表格数据
const tableList = ref<any>();

// 查询参数
const articleSearchParams = ref<any>({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  articleId: undefined,
  articleTitle: undefined,
  categoryId: undefined
});

const total = ref<number>(0);

/** 重置搜索参数 */
const articleResetSearchParams = () => {
  articleSearchParams.value = {
    pageNo: 1,
    pageSize: 10,
    articleId: undefined,
    articleTitle: undefined,
    categoryId: undefined
  };
};

/** 搜索 */
const handleArticleSearch = () => {
  articleSearchParams.value.pageNo = 1;
  handleTableData();
};

/** 重置 */
const resetArticleSearch = () => {
  articleResetSearchParams();
  handleListPage();
};

// 选择文章
const articleId = ref([]);
// 添加单/多个文章
const chooseArticleList = ref([]);

/** 表格是否多选 */
const handleArticleSelectionChange = (selection: any) => {
  console.log(selection);
  articleId.value = [];
  if (switchStatus.value === 0 || switchStatus.value > 2) {
    koiMsgWarning("请刷新重试");
    return;
  }
  // 目录类型为文章：选择单个文章
  if (switchStatus.value === 1) {
    nextTick(() => {
      if (selection.length !== 1) {
        koiMsgWarning("请选择一篇文章");
        return;
      }
      articleId.value = selection.map((item: any) => item.articleId);
    });
  }
  // 目录类型为目录：选择单/多选文章
  if (switchStatus.value === 2) {
    nextTick(() => {
      if (selection.length === 0) {
        koiMsgWarning("请选择单/多个文章");
        return;
      }
      articleId.value = selection.map((item: any) => item.articleId);
      chooseArticleList.value = selection.map((item: any) => ({
        articleId: item.articleId,
        articleTitle: item.articleTitle
      }));
    });
  }
};

const articleLoading = ref(false);

/** 数据表格 */
const handleListPage = async () => {
  try {
    tableList.value = []; // 重置表格数据
    articleLoading.value = true;
    const res: any = await listLibraryChooseArticlePage(articleSearchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
    articleLoading.value = false;
    return true; // 返回一个值来表示成功完成
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
    return false; // 返回一个值来表示失败
  }
};

/** 数据表格[不带Loading，删除、批量删除等使用] */
const handleTableData = async () => {
  try {
    const res: any = await listLibraryChooseArticlePage(articleSearchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

// 类型多选下拉框
const categoryOptions = ref();

const handleListCategoryElSelect = async () => {
  try {
    categoryOptions.value = [];
    const res: any = await listCategoryElSelect();
    categoryOptions.value = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError("级联数据查询失败，请重试");
  }
};

/** 文章选择确定 */
const handleDialogConfirm = async () => {
  if (switchStatus.value === 0 || switchStatus.value > 2) {
    koiMsgWarning("请重新刷新浏览器页面");
  }
  // 目录类型为文章：选择单个文章
  if (switchStatus.value === 1) {
    if (articleId.value.length != 1) {
      koiMsgWarning("请选择一篇文章，您选择了" + articleId.value.length + "篇");
      return;
    }
    try {
      confirmLoading.value = true;
      await updateArticleId(catalogId.value, articleId.value[0]);
      koiMsgSuccess("操作成功");
      confirmLoading.value = false;
      koiDialogRef.value.koiQuickClose();
      handleTreeData();
    } catch (error) {
      console.log(error);
      confirmLoading.value = false;
      koiMsgError("操作失败，请刷新重试");
    }
  }

  // 目录类型为目录：选择单/多选文章
  if (switchStatus.value === 2) {
    if (articleId.value.length === 0) {
      koiMsgWarning("请选择文章");
      return;
    }
    try {
      confirmLoading.value = true;
      await batchAdd(catalogId.value, routeParam.value, chooseArticleList.value);
      koiMsgSuccess("操作成功");
      confirmLoading.value = false;
      koiDialogRef.value.koiQuickClose();
      handleTreeData();
    } catch (error) {
      console.log(error);
      confirmLoading.value = false;
      koiMsgError("操作失败，请刷新重试");
    }
  }
};

/** 选择多个文章 */
const handleChooseMultipleArticle = async (row: any) => {
  switchStatus.value = 2;
  catalogId.value = row?.catalogId ? row?.catalogId : "";
  articleSearchParams.value.articleId = row?.articleId ? row?.articleId : "";
  // 打开对话框
  koiDialogRef.value.koiOpen();
  // 等待 handleListPage 完成
  await handleListPage();
  handleListCategoryElSelect();
  // 标题
  title.value = "添加文章";
};

/** 关闭当前选项卡 */
const handleCloseCurrentTab = () => {
  console.log("关闭当前选项卡");
  if (route.meta?.isAffix == "0") return;
  tabsStore.removeTab(route.fullPath);
};

/** 返回 */
const handleBack = () => {
  handleCloseCurrentTab();
  router.push("/blog/library");
};
</script>

<style lang="scss" scoped></style>
